package cn.wolfcode.luowowo.search.service;

import cn.wolfcode.luowowo.article.domain.Route;
import cn.wolfcode.luowowo.article.domain.Theme;
import cn.wolfcode.luowowo.search.domain.DestinationTemplate;
import cn.wolfcode.luowowo.search.domain.RouteTemplate;
import cn.wolfcode.luowowo.search.query.DestintionQuery;
import cn.wolfcode.luowowo.search.repository.DestinationTemplateRepository;
import cn.wolfcode.luowowo.search.repository.RouteTemplateRepository;
import cn.wolfcode.luowowo.search.vo.DestFilter;
import cn.wolfcode.luowowo.search.vo.ThemeVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class RouteServiceImpl implements IRouteSearchService {

    @Autowired
    private RouteTemplateRepository repository;
    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private DestinationTemplateRepository destinationTemplateRepository;

    @Override
    public void saveOrUpdate(RouteTemplate routeTemplate) {
        repository.save(routeTemplate);
    }

    //返回各分类下的前十六个标签
    @Override
    public Map<String,List<ThemeVo>> selectThemeSixteenForTheme() {
        Map<Long, List<ThemeVo>> map = selectAllTheme();
        Map<String, List<ThemeVo>> newMap =new LinkedHashMap<>();
        List<ThemeVo> list1 = map.get(Theme.ALL_RIGHT_SORT);
        List<ThemeVo> list2 = map.get(Theme.SEASON_SORT);
        List<ThemeVo> list3 = map.get(Theme.TRIP_SORT);
        List<ThemeVo> list4 = map.get(Theme.HOLIDAY_SORT);
        newMap.put("all",subList(list1,16));
        newMap.put("season",subList(list2,16));
        newMap.put("trip",subList(list3,16));
        newMap.put("holiday",subList(list4,16));
        return newMap;
    }
    //获取各月份前七目的地
    @Override
    public Map<String, List<DestinationTemplate>> selectBySevenMonth() {
        Map<String, List<DestinationTemplate>> map = new LinkedHashMap<>();
        for (String month:Route.getMonth()) {
            List<DestinationTemplate> list = selectDestByMonth(month);
            map.put(month,subList(list,7));
        }
        return map;
    }
    //获取所有标签
    @Override
    public Map<Long, List<ThemeVo>> selectAllTheme() {
        Map<Long, List<ThemeVo>> map = new LinkedHashMap <>();
        List<ThemeVo> list1 = selectBySort(Theme.ALL_RIGHT_SORT);
        List<ThemeVo> list2 = selectBySort(Theme.SEASON_SORT);
        List<ThemeVo> list3 = selectBySort(Theme.TRIP_SORT);
        List<ThemeVo> list4 = selectBySortWithHoliday(Theme.HOLIDAY_SORT);
        map.put(Theme.ALL_RIGHT_SORT,list1);
        map.put(Theme.SEASON_SORT,list2);
        map.put(Theme.TRIP_SORT,list3);
        map.put(Theme.HOLIDAY_SORT,list4);
        return map;
    }
    //按条件查询显示
    @Override
    public Page<RouteTemplate> selectDest(DestintionQuery qo) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        Long theme = qo.getTheme();
        Long time = qo.getTime();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (theme!= 0) {
            TermQueryBuilder themeId = QueryBuilders.termQuery("themeId", theme);
            boolQueryBuilder.must(themeId);
        }
        if(time!=0){
            TermQueryBuilder bestTimeId = QueryBuilders.termQuery("bestTimeId", time);
            boolQueryBuilder.must(bestTimeId);
        }
        Long day = qo.getDay();
        if(day !=null&&day!=0){
            int gte=2;
            int lte=3;
            if(day==2){
                gte=4;
                lte=5;
            }else if(day==3){
                gte=6;
                lte=9;
            }else if(day==4){
                gte=10;
                lte=Integer.MAX_VALUE;
            }
                RangeQueryBuilder days = QueryBuilders.rangeQuery("days").lte(lte).gte(gte);
                boolQueryBuilder.must(days);
        }
        builder.withQuery(boolQueryBuilder);
        builder.withPageable(qo.getPageable());
        Page<RouteTemplate> search = repository.search(builder.build());
        return search;
    }
/*
    //按条件查询显示
    @Override
    public Page<RouteTemplate> selectDest(DestintionQuery qo) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        Long theme = qo.getTheme();
        Long time = qo.getTime();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (theme!= 0) {
            TermQueryBuilder themeId = QueryBuilders.termQuery("themeId", theme);
            boolQueryBuilder.must(themeId);
        }
        if(time!=0){
            TermQueryBuilder bestTimeId = QueryBuilders.termQuery("bestTimeId", time);
            boolQueryBuilder.must(bestTimeId);
        }
        Long day = qo.getDay();
        if(day !=null&&day!=0){
            int gte=2;
            int lte=3;
            if(day==2){
                gte=4;
                lte=5;
            }else if(day==3){
                gte=6;
                lte=9;
            }else if(day==4){
                gte=10;
                lte=19999;
            }
                RangeQueryBuilder days = QueryBuilders.rangeQuery("days").lte(lte).gte(gte);
                boolQueryBuilder.must(days);
        }
        builder.withQuery(boolQueryBuilder);
        builder.withPageable(qo.getPageable());
        Page<RouteTemplate> search = repository.search(builder.build());
        return search;
    }
*/

    @Override
    public List<RouteTemplate> selectByDestId(Long destId) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.termQuery("destId",destId));
        builder.withPageable(PageRequest.of(0,3, Sort.Direction.DESC,"hotNum"));
        List<RouteTemplate> content = repository.search(builder.build()).getContent();
        return content;
    }

    //获取节假日的对象（封装对像有些问题）
    private List<ThemeVo> selectBySortWithHoliday(Long holidaySort) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.termQuery("bestTimeSort","节假"));
        List<RouteTemplate> content = repository.search(builder.build()).getContent();

        DestFilter destFilter = new DestFilter();
        ArrayList<ThemeVo> themes = new ArrayList<>();
        ArrayList<Long> longs = new ArrayList<>();
        for (RouteTemplate r:content) {
            if(longs.contains(r.getThemeId())){
                continue;
            }
            ThemeVo theme = new ThemeVo();
            theme.setId(r.getBestTimeId());
            theme.setCoverUrl(r.getBestTimeoverUrl());
            theme.setTheme(r.getBestTimeName());
            //theme.setSort(r.getBestTimeSort());
            themes.add(theme);
            longs.add(r.getThemeId());
        }
        return themes;
    }


    //根据路线下的最佳月份查询游记，返回目的地集合
    public List<DestinationTemplate> selectDestByMonth(String month){
        List<RouteTemplate> routeTemplates = repository.findByBestTimeName(month);
        ArrayList<Long> longs = new ArrayList<>();
        ArrayList<DestinationTemplate> list = new ArrayList<>();
        for(RouteTemplate rt:routeTemplates){
            Long destId = rt.getDestId();
            if(longs.contains(destId)){
                continue;
            }
            DestinationTemplate destinationTemplate = destinationTemplateRepository.findById(destId).get();
            list.add(destinationTemplate);
            longs.add(destId);
        }
        return list;
    }

    //按长度剪切list
    private <E> List<E> subList(List<E>  list,Integer size){
        List<E> newList = new ArrayList<>();
        if(list.size()>size){
            List<E> themeVos = list.subList(0, size);
            newList.addAll(themeVos);
            return newList;
        }
        return list;
    }
    //查询主题下的标签
    public List<ThemeVo> selectBySort(Long sort) {
        List<RouteTemplate> routeTemplates=repository.findByThemeSortId(sort);
        DestFilter destFilter = new DestFilter();
        ArrayList<ThemeVo> themes = new ArrayList<>();
        ArrayList<Long> longs = new ArrayList<>();
        for (RouteTemplate r:routeTemplates) {
            if(longs.contains(r.getThemeId())){
                continue;
            }
            ThemeVo theme = new ThemeVo();
            theme.setId(r.getThemeId());
            theme.setCoverUrl(r.getThemeCoverUrl());
            theme.setTheme(r.getThemeName());
            theme.setSort(r.getThemeSortId());
            themes.add(theme);
            longs.add(r.getThemeId());
        }
        return themes;
    }
}
